package com.hfi.restful.web.register;

import com.hfi.security.core.exception.ErrorCode;
import com.hfi.security.core.exception.SecurityCoreException;
import com.hfi.security.core.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author ChangLiang
 * @date 2019/8/16
 */
@Service
public class CustomUserService {

    public static final int USER_LEVEL_REGISTER = 1;
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CustomUserRepository customUserRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public static final int PASSWORD_MAX_LENGTH = 20;
    public static final int PASSWORD_MIN_LENGTH = 8;

    public CustomUser registerCustomUser(CustomUser customUserRequest) {

        /// 前端做了des对称加密 这里为了简单 先不做
        // String pass = DesUtil.decrypt(customUserRequest.getPasswd());
        String pass = customUserRequest.getPasswd();
        validatePassword(pass == null, ErrorCode.PASSWORD_SET, pass.length() < PASSWORD_MIN_LENGTH, ErrorCode.PASSWORD_SHORT, pass.length() > PASSWORD_MAX_LENGTH, ErrorCode.PASSWORD_LONG);
        if (!Utils.matchPassword(pass)) {
            throw new SecurityCoreException(ErrorCode.PASSWORD_E);
        }

        CustomUser customUser;
        // 手机号+密码注册 或 手机号+验证码注册
        if (customUserRequest.getMobile() != null) {
            if (!Utils.isMobile(customUserRequest.getMobile())) {
                throw new SecurityCoreException(ErrorCode.MOBILE_CHECK_ERROR);
            }
            CustomUser byMobile = customUserRepository.getByMobile(customUserRequest.getMobile());
            if (byMobile != null) {
                throw new SecurityCoreException(ErrorCode.USER_EXIST);
            }
            customUser = new CustomUser();
            customUser.setMobile(customUserRequest.getMobile());
        } else {
            // 用户名+密码注册
            customUser = getCustomUser(customUserRequest);
        }
        customUser.setPasswd(passwordEncoder.encode(pass));
        // 设置默认用户级别
        customUser.setUserLevel(USER_LEVEL_REGISTER);

        CustomUser user = customUserRepository.save(customUser);
        logger.info("操作成功:{}", customUser.toString());

        // 这个地方 browser应该返回跳转地址  app应该返回token
        return user;
    }

    private CustomUser getCustomUser(CustomUser customUserRequest) {
        CustomUser customUser;
        customUser = new CustomUser();
        // 用户名 密码注册（模拟用户名是证件号）
        // 验证
        customUser.setCustName(customUserRequest.getCustName());
        // 更新customUser
        CustomUser byCustName = customUserRepository.getByCustName(customUserRequest.getCustName());
        if (byCustName != null) {
            customUser.setCustUserId(byCustName.getCustUserId());
        }
        return customUser;
    }

    public CustomUser updateCustomUser(CustomUser customUserRequest) {

        /// 前端做了des对称加密 这里为了简单 先不做
        // String pass = DesUtil.decrypt(customUserRequest.getPasswd());
        String pass = customUserRequest.getPasswd();
        if (pass == null) {
            throw new SecurityCoreException((ErrorCode.PASSWORD_SET));
        }

        // 密码只支持8至20位、数字+英文字母组合
        validatePassword(pass.length() < PASSWORD_MIN_LENGTH, ErrorCode.PASSWORD_SHORT,
                pass.length() > PASSWORD_MAX_LENGTH, ErrorCode.PASSWORD_LONG, !Utils.matchPassword(pass),
                ErrorCode.PASSWORD_E);

        CustomUser customUser;
        // 手机号修改密码
        if (customUserRequest.getMobile() != null) {
            if (!Utils.isMobile(customUserRequest.getMobile())) {
                throw new SecurityCoreException(ErrorCode.MOBILE_CHECK_ERROR);
            }
            customUser = customUserRepository.getByMobile(customUserRequest.getMobile());
            if (customUser == null) {
                throw new SecurityCoreException(ErrorCode.USER_NOT_EXIST);
            }
        } else {
            // 用户名修改密码
            customUser = getCustomUser(customUserRequest);
        }
        customUser.setPasswd(passwordEncoder.encode(pass));

        CustomUser user = customUserRepository.save(customUser);
        logger.info("设置密码成功:{}", customUser.toString());

        // 这个地方 browser应该返回跳转地址  app应该返回token
        return user;
    }

    private void validatePassword(boolean b, ErrorCode passwordShort, boolean b2, ErrorCode passwordLong, boolean b3,
                                  ErrorCode passwordE) {
        if (b) {
            throw new SecurityCoreException(passwordShort);
        }
        if (b2) {
            throw new SecurityCoreException(passwordLong);
        }
        if (b3) {
            throw new SecurityCoreException(passwordE);
        }
    }

    public CustomUser getByCustName(String custName) {
        return customUserRepository.getByCustName(custName);
    }
}
